package cn.calm.xhtml.impl.ui;

import java.util.Arrays;

import cn.calm.xhtml.annotation.Attribute;
import cn.calm.xhtml.annotation.Tag;
import cn.calm.xhtml.api.exception.XhtmlException;
import cn.calm.xhtml.api.service.XhtmlContext;
@Tag(namespace = "http://www.calm.cn/xhtml/extras/ui", attributes = {
		@Attribute(name = "items", description = "列表选项", template = "<label></label><input name=\"items\"/>"),
		@Attribute(name = "valueProperty", description = "提交值属性", template = "<label></label><input name=\"valueProperty\"/>"),
		@Attribute(name = "textProperty", description = "展示值属性", template = "<label></label><input name=\"textProperty\"/>"),
		@Attribute(name = "label", description = "展示标签", template = "<label></label><input name=\"label\"/>")})
public class RadioButtons extends InputNode {
	public static final String KEYS_ITEMS = "items";

	public static final String KEYS_VALUE_PROPERTY = "valueProperty";

	public static final String KEYS_TEXT_PROPERTY = "textProperty";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void processNode(XhtmlContext context) throws XhtmlException {
		Object value = getAttrValue("items", context);

		Iterable<?> ite = null;
		if (value instanceof Iterable) {
			ite = (Iterable<?>) value;
		} else if (value instanceof Object[]) {
			ite = Arrays.asList((Object[]) value);
		} else {
			throw new XhtmlException("items is not Iterable");
		}

		String property = getAttr(KEYS_VALUE_PROPERTY);
		if (property == null) {
			throw new XhtmlException();
		}
		String text = getAttr(KEYS_TEXT_PROPERTY);
		if (text == null) {
			throw new XhtmlException();
		}
		Object nameObj = getAttrValue(KEYS_NAME, context);
		String name = null;
		if (nameObj != null) {
			name = nameObj.toString();
		}
		
		Object attrValue = getAttrValue(KEYS_VALUE, context);
		context.setValue("tempValue", attrValue);
		Radio r;
		for (Object o : ite) {

			context.setValue("r", o);

			r = new Radio();

			r.setAttr("value", "${r." + property + "}");
			
			r.setAttr("label", "${r." + text + "}");
			
			r.setAttr(Radio.KEYS_CHECKED, "${r." + property + " == tempValue}");
			
			r.setAttr("name", name);
			r.processNode(context);
		}
	}

}
